package vip.xiaonuo.biz.modular.lancerRegister;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vip.xiaonuo.auth.api.SaBaseLoginUserApi;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.biz.modular.lancerBrand.service.BizBrandService;
import vip.xiaonuo.biz.modular.pojo.domain.BizBrand;
import vip.xiaonuo.common.pojo.DbEnum;
import vip.xiaonuo.common.pojo.UserRegisterDTO;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.util.CommonCryptogramUtil;
import vip.xiaonuo.sys.feign.SysUserFeign;

import javax.annotation.Resource;


@Service
public class MyLoginService {
    @Autowired
    BizBrandService brandService;
    @Resource
    private SaBaseLoginUserApi loginUserApi;
    @Autowired
    SysUserFeign sysUserFeign;

    public void preCheck(String account, String password, String password2, String role) {
        SaBaseLoginUser saBaseLoginUser = loginUserApi.getUserByAccount(account);
        String pwd1 = CommonCryptogramUtil.doHashValue(CommonCryptogramUtil.doSm2Decrypt(password));
        String pwd2 = CommonCryptogramUtil.doHashValue(CommonCryptogramUtil.doSm2Decrypt(password2));
        if (ObjectUtil.notEqual(pwd2, pwd1)) {
            throw new CommonException("两次密码不一致！");
        }
        if (ObjectUtil.isNotEmpty(saBaseLoginUser)) {
            throw new CommonException("账号已存在！");
        }
        DbEnum.SYS_ROLE.validate(role);
    }

    public void doRegister(UserRegisterDTO dto) {
        // 校验
        preCheck(dto.getAccount(), dto.getPassword(), dto.getPassword2(), dto.getRole());
        // 远程调用web服务
        sysUserFeign.addUser(dto);
        // 如果是品牌方
        if (DbEnum.SYS_ROLE.BRAND.getValue().equals(dto.getRole())){
            // 获取返回的用户id(即品牌id)
            String userId= sysUserFeign.getUserIdByAccount(dto.getAccount());
            // 操作品牌表
            BizBrand brand = new BizBrand();
            BeanUtils.copyProperties(dto,brand);
            brand.setId(userId)
                    .setCreateUser(userId);
            brand.setBrandStatus(DbEnum.BrandStatus.NORMAL.getValue());
            brandService.save(brand);
        }
    }
}
